﻿using System;
using System.Diagnostics;
using TimeSnapperPluginAPI;
using System.Net;
using System.Xml;
using System.IO;

namespace SamplePlugins
{
    public class FlagHelpers
    {
        public static int SaveFlagsFromRss(IServices services, string xml, int flagColor)
        {
            int count = 0;
            string title;
            DateTime pubDate;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            XmlNodeList nodes;
            nodes = doc.SelectNodes("rss/channel/item");

            foreach (XmlNode node in nodes)
            {
                XmlNode child;

                child = node.SelectSingleNode("title");
                if (child == null) continue;
                title = child.InnerText;

                child = node.SelectSingleNode("pubDate");
                if (child == null) continue;
                pubDate = DateTime.Parse(child.InnerText);

                // strip the seconds part
                pubDate = new DateTime(pubDate.Year, pubDate.Month, pubDate.Day, pubDate.Hour, pubDate.Minute, 0);

                SaveFlag(services, title, pubDate, flagColor);

                count++;
            }

            return count;
        }

        private static void SaveFlag(IServices services, string comment, DateTime flagDate, int flagColor)
        {
            Flag f = services.FlagServices.GetFlag(flagDate);

            if (f.FlagId == 0)
            {
                // it's a new flag completely
                f.FlagDate = flagDate;
                f.Comment = comment;
                f.Color = System.Drawing.Color.FromArgb(flagColor);
                f.FlagType = "NOTE";
                services.FlagServices.SaveFlag(f);
            }
            else
            {
                if (f.Comment == string.Empty)
                {
                    f.Comment = comment;
                    services.FlagServices.SaveFlag(f);
                }
                else if (f.Comment.IndexOf(comment) < 0)
                {
                    f.Comment += System.Environment.NewLine + comment;
                    services.FlagServices.SaveFlag(f);
                }
            }
        }
    }
}
